<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\user as UserModel;
use think\Request;
use app\model\Auth as AuthModel;
use app\model\Role as RoleModel;
use app\middleware\Auth as AuthMiddleware;
use think\facade\View;
class Auth
{

    protected $middleware = [AuthMiddleware::class];

    private $toast = 'public/toast';
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = AuthModel::with(['role'])->withSearch(['name'],[
            'name' => request()->param('name')
        ])->paginate([
            'list_rows'=> 5,
            'query' => request()->param()
        ]);

        //第一层遍历
        foreach ($list as $key=>$obj) {
            //第二层遍历
            foreach ($obj->role as $r) {
                $obj->roles .= $r->type.' | ';
            }
            //去尾
            $obj->roles = trim(substr(trim($obj->roles), 0, -1));
        }


        return view('index',[
            'list' => $list
        ]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('D:\php\phpEnv\www\www.tp.com\view\auth\create.html',[
            'list' => RoleModel::select(),

        ]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $request->param();
        //验证新增管理员表
        $data['password'] = sha1($data['password']);
        //新增
        $id = AuthModel::create($data)->getData('id');
        //关联新增
        AuthModel::find($id)->role()->saveAll($data['role']);
        //提示
        return $id ? view($this->toast, [
            'infos' => ['恭喜，添加成功！'],
            'url_text' => '去权限页',
            'url_path' => url('/auth')
        ]) : '添加失败！';
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
